/**
 * Created by Oswald on 2016/12/30.
 */

var BOMID = -1;
var verId = -1;
var AddBOMDiv =  -1;
var CopyBOMDiv = -1;
var addedBomId = -1;
var status = '';
$(document).ready(function() {
    //设置右边底部DIV高度
    setRightBottomH();

    //设置所有按钮不可用
    $(".btn-toolbar").find("button").attr("disabled", true);
    $("#addBOMBtn").attr("disabled", false);

    //搜索按钮事件
    $("#BOMSearchBtn").click(function(){
        addedBomId = -1;
        GetBOMData();
    });

    //新增BOM按钮事件
    $("#addBOMBtn").click(function(){
        BomAdd.Call();
    });

    //拷贝BOM按钮事件
    $("#copyBOMBtn").click(function(){
        BomCopy.Call();
    });

    //删除BOM按钮事件
    $("#deleteBOMBtn").click(function(){
        TuLayer.ShowConfirm("确定要删除BOM吗？",function(){
            Signature.CallSign(100,function(sid){
                var param = {"id":BOMID,"sid":sid};
                var serverUrl = serverPath + "Boms/delete/";
                ibcpAjax.Delete(serverUrl,param,true,function(result){
                    Signature.CloseSign();
                    TuLayer.ShowOK("删除成功!");
                    GetBOMData();
                });
            });
        });
    });

    //查看当前版本信息按钮
    $("#currentVersionBtn").click(function(){
        var url = "../Version/VersionDetailCheck.html";
        TuLayer.ShowDiv(url, 'BOM版本详细信息', '400px', '370px',function() {
            $("#VersionDetailTable").bootstrapTable();
            loadVersionDetailData();

            $("#btnVSDetailClose").on('click',function(){
                TuLayer.Close();
            });
        });
    });

    //升级版本
    $("#updateVersionBtn").click(function(){
        BomUpdateVersion.Call();
    });

    //查看历史版本按钮
    $("#historyVersionBtn").click(function(){
        var url = "../Version/ObjectVersionHistory.html";
        TuLayer.ShowDiv(url, 'BOM版本历史信息', '900px', '380px',function() {
            $("#VersionHistoryTable").bootstrapTable();
            loadDataForObjHistory();

            $("#btnVSHistoryClose").on('click',function(){
                TuLayer.Close();
            });
        });
    });

    //状态转移 按钮事件
    $('#changeStatusBtn').click(function() {
        var url = "../Version/ObjectStateChange.html";
        TuLayer.ShowDiv(url, '状态转移', '420px', '480px',function() {
            LoadVCInfo();
            $("#btnVCSave").on('click',function(){
                VSCEnsure();
            });
            $("#btnVSCancel").on('click',function(){
                TuLayer.Close();
            });
        });

    });

    //修改BOM备注
    $("#editCommentBtn").click(function(){
        var comment = $("#productComment").val();
        if(comment == ''){
            TuLayer.ShowTips('请输入备注',$("#productComment"));
            return;
        }

        var updateBomUrl = serverPath + "Boms/updateBom";
        Signature.CallSign(100,function(sid){
            var param = {"id": BOMID, "description": comment, "sid": sid};
            ibcpAjax.Update(updateBomUrl,param,true,function(result){
                Signature.CloseSign();
                TuLayer.ShowOK("修改成功!");
                addedBomId = BOMID;
                GetBOMData();
            });
        });

    });

    //添加BOM物料项 按钮事件
    $('#addMaterialBtn').click(function() {
        BomMatAdd.Call();
    });

    //修改BOM物料项 按钮事件
    $('#editMaterialBtn').click(function() {
        BomMatEdit.Call();
    });


    //物料项查看详情按钮
    $('#detailMaterialBtn').click(function(){
        var id = GetSelectedRow($("#materialTable")).bomId;
        var itemCode = GetSelectedRow($("#materialTable")).itemCode;

        var url = "MaterialDetail.html";
        TuLayer.ShowDiv(url, '物料详情', '1000px', '150px',function(){
            $('#materialDetailTable').bootstrapTable();
            var serverUrl = serverPath + "BomsDetail/findBomDetail/";
            var param = {bomId:id,itemCode:itemCode};
            ibcpAjax.Select(serverUrl,param,true,function(result){
                var data = [];
                data.push(result.data);
                $("#materialDetailTable").bootstrapTable('load',data);
            });
        });

    });

    //删除物料项按钮事件
    $("#deleteMaterialBtn").click(function(){
        var name = GetSelectedRow($("#materialTable")).name;
        var code = GetSelectedRow($("#materialTable")).code;
        var msg = "确定要删除物料项"+name+"("+code+")"+"吗？";
        TuLayer.ShowConfirm(msg,function(){
            Signature.CallSign(100,function(sid){
                var itemCode = GetSelectedRow($("#materialTable")).itemCode;
                var param = {"bomId":BOMID,"sid":sid,"itemCode":itemCode};
                var serverUrl = serverPath + "BomsDetail/deleteBomDetail/";
                ibcpAjax.Delete(serverUrl,param,true,function(result){
                    Signature.CloseSign();
                    TuLayer.ShowOK("删除成功!");
                    RefreshMaterial();
                });
            });
        });
    });

    //单击行触发的事件
    $('table').on('click-row.bs.table', function (e, row, element){

        $('.selected').removeClass('selected');//去除之前选中的行的，选中样式
        $(element).addClass('selected');//添加当前选中的 success样式用于区别

    });

    //选择物料项列表时按钮状态
    $('#materialTable').on('click-row.bs.table', function (e, row, element){
        $("#detailMaterialBtn").attr("disabled", false);
        if(status == "编辑"){
            $("#editMaterialBtn").attr("disabled", false);
            $("#deleteMaterialBtn").attr("disabled", false);
        }else {
            $("#editMaterialBtn").attr("disabled", true);
            $("#deleteMaterialBtn").attr("disabled", true);
        }

    });

});

$(window).resize(function(){
    setRightBottomH();
});

//重置基本状态
function ResetBaseInfoUI(){
    $(".btn-toolbar").find("button").attr("disabled", true);
    $("#addBOMBtn").attr("disabled", false);

    $("#productCode").val('');
    $("#productName").val('');
    $("#productQuantity").val('');
    $("#productQuantity").attr("quantity",'');
    $("#productQuantity").attr("uomName",'');
    $("#productVersion").val('');
    $("#productStatus").val('');
    $("#productComment").val('');

    $("#materialTable").bootstrapTable('removeAll');
}

//设置右边底部DIV高度
function setRightBottomH(){
    var dataHeight = $("#materialTableParent").height();
    $('#materialTable').bootstrapTable('refreshOptions',{height:dataHeight});
};

//获取BOM树的数据
function GetBOMData(){
    var condition = $("#BOMSearchInput").val();
    var param = {"str":condition};
    var url = serverPath + "Boms/findBom/";
    ibcpAjax.Select(url,param,true,AnalysisData);
}

//解析数据
function AnalysisData(callbackdata){
    var data = JSON.parse(callbackdata.data);//json字符串转为Json对象
    //如果没有数据，清空右边之前显示的基本数据
    if(data.length == 0){
        ResetBaseInfoUI();
    }

    var treeData = [];//BOM树的数据
    for (var i=0;i<data.length;i++){
        var BOM = data[i];
        var bomInfoArray = BOM.bom;
        var code = BOM.code;
        var bomJson = {};

        //根节点的显示文本，并设置为不可选中
        bomJson.text = code;
        bomJson.selectable = false;

        //子节点的json数组
        var bomChildArr = [];
        for (var j=0;j<bomInfoArray.length;j++){
            var bomInfo = bomInfoArray[j];
            var id = bomInfo.id;
            var version = bomInfo.version;
            var quantity = bomInfo.quantity;
            var status = bomInfo.status;
            var symbol = bomInfo.symbol;


            //每一个子节点的显示文本，id,状态
            var bomChildJson = {};
            bomChildJson.text = "批量:" + quantity + "(" + symbol + ")" + "----版本:" + version;
            bomChildJson.id = id;
            bomChildJson.tags = [status];
            bomChildJson.baseInfo = bomInfo;
            //设置初始化选中第一条
            if (i == 0 && j == 0 && addedBomId == -1){
                bomChildJson.state = {selected:true};
                verId = bomInfo.verId;
                BOMID = id;
                GetBomBaseInfo(id);
            }

            //新增后，默认选中新增的数据
            if (id == addedBomId){
                bomChildJson.state = {selected:true};
                verId = bomInfo.verId;
                BOMID = id;
                GetBomBaseInfo(id);
            }

            bomChildArr.push(bomChildJson);
        }
        bomJson.nodes = bomChildArr;
        treeData.push(bomJson);
    }

    InsertDataToTree(treeData);
    //滚动到被选中的位置
    scrollToLocation();
};

//填充树
function InsertDataToTree(treeData){
    //数据填充到树中
    $("#BOMTree").treeview({
        showTags: true,
        data:treeData,
        multiSelect:false,
        selectedBackColor:"#009688",
        //选中子节点事件
        onNodeSelected:function(event,data){
            //var nodes = $("#BOMTree").find("ul").find("li");
            var id = data.nodeId;
            var at = "li[data-nodeid={0}]";
            var node =  $("#BOMTree").find("ul").find(at.format(id));
            var t = node.position().top;
            var f = node.offset().top;
            var p = node.offsetParent().offset();

            BOMID = data.id;
            GetBomBaseInfo(BOMID);
        }
    });
};

String.prototype.format = function () {
    if (arguments.length == 0) return this;
    for (var s = this, i = 0; i < arguments.length; i++)
        s = s.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
    return s;
}

//treeview滚动到指定位置
function scrollToLocation() {
    var treeFather = $('#BOMTreeFather');
    var treeFatherH = treeFather.height();//树结构父Div元素的高度
    var treeH = $("#BOMTree").height();//整个树的总高度

    //通过类去寻找被选中的节点
    var node = $("#BOMTree").find("ul").find("li.node-selected");
    var nodeid = node.attr('data-nodeid');

    //节点的高度
    var nodeH = node.outerHeight(true);

    //节点的偏移量加高度  当前节点数乘以每个节点的高度
    var nodeTH = nodeid * nodeH;

    //树结构父Div元素的高度的一半
    var haltTreeF = treeFatherH * 0.5;

    //判断是否需要滚动
    if(nodeTH <= haltTreeF){
        return;
    }

    //最大偏移量
    var maxOffset = treeH - treeFatherH;

    //如果超过最大偏移量，就按照最大偏移量来滚动
    if(nodeTH >= maxOffset){
        treeFather.animate({
            scrollTop:maxOffset
        },500);
    }else {
        var offset = nodeTH - haltTreeF;
        treeFather.animate({
            scrollTop:offset
        },500);
    }

}

//获取BOM基本信息
function GetBomBaseInfo(bomID){
    var param = {"id":bomID};
    var url = serverPath + "Boms/findById";

    ibcpAjax.Select(url,param,true,ShowBomBaseInfo);
};

//显示BOM基本信息
function  ShowBomBaseInfo(baseData){
    var baseInfo = baseData.data;
    var code = baseInfo.code;
    var name = baseInfo.name;
    var quantity = baseInfo.quantity;
    var symbol = baseInfo.symbol;
    var version = baseInfo.version;
    status = baseInfo.status;
    var description = baseInfo.description;

    verId = baseInfo.verId;

    $("#productCode").val(code);
    $("#productName").val(name);
    $("#productQuantity").val(quantity + "(" + symbol + ")");
    $("#productQuantity").attr("quantity",quantity);
    $("#productQuantity").attr("uomName",symbol);
    $("#productVersion").val(version);
    $("#productStatus").val(status);
    $("#productComment").val(description);


    var material = baseInfo.bomDetails;
    $("#materialTable").bootstrapTable('load',material);

    SetButtonStatus();

};

//刷新物料项列表
function RefreshMaterial(newId){
    var param = {"bomId":BOMID};
    var url = serverPath + "BomsDetail/findBomDetailById/";

    ibcpAjax.Select(url,param,true,function(result){
        $("#materialTable").bootstrapTable('load',result.data);
        if(result.data.length >0) {
            //定位新增行
            $("#materialTable").bootstrapTable("checkBy", {field:"itemCode", values:[newId]});
        }
    });
};

//设置按钮可用状态
function SetButtonStatus(){
    $("#addBOMBtn").attr("disabled", false);
    $("#currentVersionBtn").attr("disabled", false);
    $("#historyVersionBtn").attr("disabled", false);

    $("#detailMaterialBtn").attr("disabled", true);
    $("#editMaterialBtn").attr("disabled", true);
    $("#deleteMaterialBtn").attr("disabled", true);


    if (status == "编辑"){
        $("#deleteBOMBtn").attr("disabled", false);
        $("#editCommentBtn").attr("disabled", false);
        $("#addMaterialBtn").attr("disabled", false);
    }else {
        $("#deleteBOMBtn").attr("disabled", true);
        $("#changeStatusBtn").attr("disabled", true);
        $("#editCommentBtn").attr("disabled", true);
        $("#addMaterialBtn").attr("disabled", true);
    }

    if(status == "失效"){
        $("#changeStatusBtn").attr("disabled", true);
        $("#copyBOMBtn").attr("disabled", true);
        $("#updateVersionBtn").attr("disabled", true);
    }else {
        $("#changeStatusBtn").attr("disabled", false);
        $("#copyBOMBtn").attr("disabled", false);
        $("#updateVersionBtn").attr("disabled", false);
    }
};

//获取选中行数据
function GetSelectedRow(table)
{
    var index = table.find('tr.selected').data('index');//获得选中的行
    return table.bootstrapTable('getData')[index];//返回选中行所有数据
}

/*****************************************************   新增 BOM    ****************************************************/

;var BomAdd = (function(){

    function Call(){
        var url = "AddBOM.html";
        TuLayer.ShowDiv(url, '新增BOM', '400px', '500px',function(){
            //选择产品代码和名称按钮监听
            $('#selectProductBtn').on('click',function(){
                ibcpSelectProduct.CallProduct(GetSelectProduct);
            });
            //选择单位
            $('#selectUnitBtn').on('click',function(){
                //选择单位，传入回调函数
                ibcpUom.CallUom(function(uomData){
                    $('#addProductUnit').val(uomData.symbol);
                    $('#addProductUnit').attr('unitId',uomData.id);
                });
            });
            //确认
            $('#addBomEnsureBtn').on('click',function(){
                AddBomEnsure();
            });
        });
    }

    //获取选中的数据，填充到添加的表单中
    function GetSelectProduct(selectedData){
        var code = selectedData.code;
        var name = selectedData.name;
        $("#addProductCodeInput").val(code + "(" + name + ")");
        $("#addProductCodeInput").attr("codeId",selectedData.id);
        $("#addProductCodeInput").attr("code",code);
        $("#addProductNameInput").val(name);
    }

    //确认添加BOM按钮
    function AddBomEnsure(){
        var codeId = $("#addProductCodeInput").attr('codeId');
        var code = $("#addProductCodeInput").attr('code');
        var name =  $("#addProductNameInput").val();
        var quantity = $("#addProductQuantity").val();
        var unitId = $("#addProductUnit").attr('unitId');
        var unit = $("#addProductUnit").val();
        //var unitId = "1";
        var comment = $("#addProductComment").val();
        var reason = $("#addProductReason").val();

        //非空验证
        if(code == ''){
            TuLayer.ShowTips("请选择代码！",$('#addProductCodeInput'));
            return;
        }

        if(quantity == ''){
            TuLayer.ShowTips("请输入批量！",$('#addProductQuantity'));
            return;
        }
        if(unit == ''){
            TuLayer.ShowTips("请选择单位！",$('#addProductUnit'));
            return;
        }
        if(comment == ''){
            TuLayer.ShowTips("请输入备注！",$('#addProductComment'));
            return;
        }
        if(reason == ''){
            TuLayer.ShowTips("请新增理由！",$('#addProductReason'));
            return;
        }

        Signature.CallSign(100,function(sid){
            var param = {"sdid":sid,"codeId":codeId,"quantity":quantity,"reason":reason,"description":comment,"uomId":unitId};
            var url =  serverPath + "Boms/addBom/";
            ibcpAjax.Insert(url,param,true,function(result){
                addedBomId = result.data;
                Signature.CloseSign();
                TuLayer.Close();
                GetBOMData();
            });
        });
    }

    return{
        Call:Call
    }

})();

/*****************************************************   拷贝BOM   ****************************************************/

;var BomCopy = (function(){
    function Call(){
        var url = "BOMCopy.html";
        TuLayer.ShowDiv(url, '拷贝BOM', '400px', '450px',function(){
            //选择产品代码和名称按钮监听
            $('#selectProductBtn').on('click',function(){
                ibcpSelectProduct.CallProduct(GetSelectProduct);
            });
            //选择单位监听
            $('#selectUnitBtn').on('click',function(){
                //选择单位，传入回调函数
                ibcpUom.CallUom(function(uomData){
                    $('#copyProductUnit').val(uomData.symbol);
                    $('#copyProductUnit').attr('unitId',uomData.id);
                });
            });
            //选择产品代码和名称按钮监听
            $('#copyBomEnsureBtn').on('click',function(){
                CopyBomEnsure();
            });
        });
    }

    //获取选中的数据，填充到添加的表单中
    function GetSelectProduct(selectedData){
        var code = selectedData.code;
        var name = selectedData.name;
        $("#addProductCodeInput").val(code + "(" + name + ")");
        $("#addProductCodeInput").attr("codeId",selectedData.id);
        $("#addProductCodeInput").attr("code",code);
        $("#addProductNameInput").val(name);
    }
    //确定拷贝BOM
    function CopyBomEnsure(){
        var codeId = $("#addProductCodeInput").attr('codeId');
        var quantity = $("#copyProductQuantity").val();
        var reason = $("#copyProductReason").val();

        Signature.CallSign(100,function(sid){
            var param = {"sdid":sid,"codeId":codeId,"quantity":quantity,"reason":reason,"oldBomId":BOMID};
            var url =  serverPath + "Boms/copyBom/";
            ibcpAjax.Insert(url,param,true,function(result){
                addedBomId = result.data;
                Signature.CloseSign();
                TuLayer.Close();
                GetBOMData();
            });
        });
    };

    return {
        Call : Call
    }
})();

/*****************************************************   查看 BOM版本详细    ****************************************************/

// 弹出 版本详细层 获取后台数据
function loadVersionDetailData(){
    'use strict';
    var datas = {'id': verId};
    var url = serverPath + 'versionHistory/queryVersionHistoryById';
    ibcpAjax.Select(url, datas, true, function(result){
        var data = result.data;
        $('#Object_Detail_Version').val(data.version);
        $('#Object_Detail_Version').attr('readonly', 'readonly');
        $('#Object_Detail_State').val(data.toName);
        $('#Object_Detail_State').attr('readonly', 'readonly');
        $('#Object_Detail_StartTime').val(data.validStart);
        $('#Object_Detail_StartTime').attr('readonly', 'readonly');
        $('#Object_Detail_EndTime').val(data.validEnd);
        $('#Object_Detail_EndTime').attr('readonly', 'readonly');
        $('#Object_Detail_Operater').val(data.userName);
    });
}

/*****************************************************   查看 BOM版本历史    ****************************************************/
// 弹出层2获取后台数据
function loadDataForObjHistory(){
    'use strict';
    var datas = {'objId': BOMID, 'typeId': '2'};
    var ObjHistoryUrl = serverPath + 'versionHistory/queryVersionHistoryByTypeIdAndObjectId';
    ibcpAjax.Select(ObjHistoryUrl, datas, true, function(result){
        var data = result.data;
        $('#VersionHistoryTable').bootstrapTable('load', data);
    });
}

function VSHistoryClose(){
    layer.close(VersionHistoryBox);
}

/*****************************************************   升级 BOM版本    ****************************************************/

;var BomUpdateVersion = (function(){
    function Call(){
        var url = "BOMVersionUpdate.html";
        TuLayer.ShowDiv(url, '版本升级', '400px', '500px',function(){
            var code = $("#productCode").val();
            var name = $("#productName").val();
            var quantity = $("#productQuantity").attr('quantity');
            var uom = $("#productQuantity").attr('uomName');
            var comment = $("#productComment").val();

            $("#updateProductCodeInput").val(code);
            $("#updateProductNameInput").val(name);
            $("#updateProductQuantity").val(quantity);
            $("#updateProductUnit").val(uom);
            $("#updateProductComment").val(comment);

            //确认按钮
            $("#updateBomEnsureBtn").on('click',function(){
                BOMVersionUpdate();
            });

            //取消
            $("#updateBomCancelBtn").on('click',function(){
                TuLayer.Close();
            });
        });
    }

    function BOMVersionUpdate(){
        var reason = $("#updateProductReason").val();
        if (reason == ''){
            TuLayer.ShowTips('请输入升级理由',$("#updateProductReason"));
            return;
        }

        var updateBomVersionUrl = serverPath + 'Boms/upgradeBom';

        Signature.CallSign(100,function(sid){
            var param = {"bomId":BOMID,"reason":reason,"sid":sid};
            ibcpAjax.Insert(updateBomVersionUrl,param,true,function(result){
                TuLayer.ShowOK('升级成功');
                addedBomId = result.data;
                //关闭签名
                Signature.CloseSign();
                //关闭新增
                TuLayer.Close();
                //刷新
                GetBOMData();
            });
        });

    }

    return{
        Call : Call
    }
})();



/*****************************************************   变更 BOM版本状态    ****************************************************/
//当前版本信息
var objNowVS = '';
var ObjVersionChangeUrl = serverPath + 'versionHistory/queryVersionHistoryById';
//加载当前版本信息
function LoadVCInfo(){
    var datas = {'id': verId};
    ibcpAjax.Select(ObjVersionChangeUrl, datas, true, function(result) {
        objNowVS = result.data;
        $('#CurrentVersion').val(objNowVS.version);
        $('#CurrentStatus').val(objNowVS.toName);
        LoadAllowChangeStatusInfo(objNowVS.toStatusId, objNowVS.typeId);
    });
}

//加载可变更状态
function LoadAllowChangeStatusInfo(fromId, typeId){
    var datas = {'fromId': fromId,'typeId': typeId};
    $("#targetStatus").attr('readonly', true);
    $("#ValidDateStart").attr('readonly',true);
    $("#ValidDateEnd").attr('readonly',true);
    $("#ChangeReason").attr('readonly',true);
    $("#btnVCSave").attr('disabled',true);

    var ObjVersionChangeStatusUrl = serverPath + 'versionProcess/queryOptionalState';

    ibcpAjax.Select(ObjVersionChangeStatusUrl, datas, true, function(result){
        var data = result.data
        if(data.length > 0){
            $("#targetStatus").attr('readonly', false);
            $("#ValidDateStart").attr('readonly',false);
            $("#ValidDateEnd").attr('readonly',false);
            $("#ChangeReason").attr('readonly',false);
            $("#btnVCSave").attr('disabled',false);

            for(var i=0;i<data.length;i++) {
                var toOptions = "<option value='" + JSON.stringify(data[i]) + "'>" + data[i].toName + "</option>"
                $("#targetStatus").append(toOptions);
                $("#targetStatus").val('');
            }
            //只有一个数据的时候默认选择
            if(data.length == 1){
                $("#targetStatus").prop('selectedIndex', 0);
            }

        }
        else {
            TuLayer.ShowMsgCB('没有可变更的状态',function(){VSCCancel();});
        }
    });
}

//版本变更确认按钮事件
function VSCEnsure(){
    var vStart ='';
    var vEnd ='';
    var status = $("#targetStatus").val();
    var start = $("#ValidDateStart").val();
    var end = $("#ValidDateEnd").val();

    if(status == null || status == ""){
        ibcpLayer.ShowTips('请选择状态',$("#targetStatus"));
        return;
    }

    if(start != null && start != ""){
        vStart = start + ' 00:00:00';
    }

    if(end != null && end != ""){
        vEnd = end + ' 23:59:59';
    }

    if(vEnd != '' && vStart != ''){
        if(vEnd <= vStart){
            ibcpLayer.ShowTips('结束日期 早于 开始日期',$("#ValidDateEnd"));
            return;
        }
    }

    //var selectToInfo = status; //选择的目标状态信息 是字符串 需要转Json
    var selectToInfo = $.parseJSON(status); //选择的目标状态信息 是字符串 需要转Json

    var signNeedId = selectToInfo.aid;   //签名需要的ID
    var toId = selectToInfo.toId;         //目标状态ID
    var reason = $("#ChangeReason").val();

    Signature.CallSign(signNeedId,function(sid){
        var datas = {'verFlowId': objNowVS.verFlowId,
            'version': objNowVS.version,
            'fromStatusId': objNowVS.toStatusId,
            'toStatusId': toId,
            'validStart': vStart,
            'validEnd': vEnd,
            'sid': sid,
            'reason': reason,
            'objId': objNowVS.objId,
            'typeId': objNowVS.typeId
        };

        var ObjVersionAddVersionHistoryUrl = serverPath + 'versionHistory/addVersionHistory';
        //保存
        ibcpAjax.Insert(ObjVersionAddVersionHistoryUrl,datas,false,function(result){
            Signature.CloseSign();
            TuLayer.Close();
            TuLayer.ShowOK("操作成功！");
            addedBomId = BOMID;
            GetBOMData();
        });
    });
}

/*****************************************************   物料项 新增    ****************************************************/
;var BomMatAdd = (function(){
    function Call(){
        var url = "BOMMaterielAdd.html";
        TuLayer.ShowDiv(url, '添加物料项', '400px', '570px',function() {
            ListenAddBomMatEvents();
            GetAllPrecision();
        });
    }

    //监听单位选择弹出窗口 的确认和取消按钮事件
    function ListenAddBomMatEvents(){
        //选择物料
        $('#selectMatBtn').on('click',function () {
            ibcpSelectMat.CallMat(function(selectedData){
                var code = selectedData.code;
                var name = selectedData.name;
                $("#addMatCodeInput").val(code + "(" + name + ")");
                $("#addMatCodeInput").attr("codeId",selectedData.id);
                $("#addMatCodeInput").attr("code",code);
            })
        });

        //选择单位
        $('#selectUnitBtn').on('click',function () {
            //选择单位，传入回调函数
            ibcpUom.CallUom(function(uomData){
                $('#addBOMMatUnit').val(uomData.symbol);
                $('#addBOMMatUnit').attr('unitId',uomData.id);
                $('#precisionUom').text(uomData.symbol);
            });
        });

        //新增物料项确认按钮事件
        $('#addBomMatSaveBtn').on('click',function () {
            AddBomMatSaveEvent();
        });

        //新增物料项取消钮事件
        $('#addBomMatCancelBtn').on('click',function () {
            AddBomMatCancelEvent();
        });
    }

    //确认按钮事件
    function AddBomMatSaveEvent(){
        var no = $("#addBOMMatNo").val();
        var code =  $("#addMatCodeInput").attr('code');
        var codeId =  $("#addMatCodeInput").attr('codeId');
        var num =  $("#addBOMMatNum").val();
        var lock =  $("#addBOMMatNumLock").is(':checked');
        var unitName =  $("#addBOMMatUnit").val();
        var unitId = $("#addBOMMatUnit").attr("unitId");
        var wType =  $("#addBOMWeightType").val();
        var wMatType =  $("#addBOMWeightMatType").val();
        var precisionId = $('#materialPrecision').val();
        var tolType =  $("#addBOMTolType").val();
        var tolMax =  $("#addBOMTolMax").val();
        var tolMin =  $("#addBOMTolMin").val();
        var fml = $("#addBOMformula").val();

        if(code == ''){
            TuLayer.ShowTips('请选择物料',$("#addBOMMatCode"));
            return;
        }
        if(num == ''){
            TuLayer.ShowTips('请选择输入数据量',$("#addBOMMatNum"));
            return;
        }
        if(unitName == ''){
            TuLayer.ShowTips('请选择单位',$("#addBOMMatUnit"));
            return;
        }
        Signature.CallSign(100,function(sid){
            var addBomMatUrl = serverPath + 'BomsDetail/addBomDetail';
            var datas = {'sid':sid,'bomId':BOMID, 'itemCode':no, 'codeId':codeId, 'quantity':num, 'uomId':unitId, 'inDepCalc':lock,
                'weighTypeId':wType, 'materialTypeId':wMatType, 'toleranceTypeId':tolType,'precisionId':precisionId, 'toleranceUpper':tolMax, 'toleranceLower':tolMin,'potencyFormula':fml};
            ibcpAjax.Insert(addBomMatUrl,datas,true,function(result){
                TuLayer.ShowOK('新增成功');
                var newId = result.data;
                //关闭签名
                Signature.CloseSign();
                //关闭新增
                AddBomMatCancelEvent();
                //刷新定位新数据行
                RefreshMaterial(newId);

            });
        });

    }

    //单位选择确认按钮事件
    function AddBomMatCancelEvent(){
        TuLayer.Close();
    }

    return{
        Call:Call
    }
})();

//获取精度
function GetAllPrecision(){
    var url = serverPath + "precision/findAllPrecision";
    ibcpAjax.Select(url,'',true,function(result){
        var data = result.data;
        var precision = '';
        $.each(data,function(index,item){
            var id = item.id;
            var value = item.value;

            precision +="<option value='"+id+"'>"+value+"</option>"
        })
        $("#materialPrecision").append(precision);
    });
}

/*****************************************************   物料相 修改    ****************************************************/
;var BomMatEdit = (function(){
    function Call(){
        var url = "BOMMaterielEdit.html";
        TuLayer.ShowDiv(url, '编辑物料项', '420px', '570px',function() {
            GetAllPrecision();
            ListenEditBomMatEvents();
            LoadBomMatInfo();
        });
    }

    //监听单位选择弹出窗口 的确认和取消按钮事件
    function ListenEditBomMatEvents(){
        //选择物料
        $('#selectMatBtn').on('click',function () {
            ibcpSelectMat.CallMat(function(selectedData){
                var code = selectedData.code;
                var name = selectedData.name;
                $("#editMatCodeInput").val(code + "(" + name + ")");
                $("#editMatCodeInput").attr("codeId",selectedData.id);
                $("#editMatCodeInput").attr("code",code);
            })
        });

        //选择单位
        $('#selectUnitBtn').on('click',function () {
            //选择单位，传入回调函数
            ibcpUom.CallUom(function(uomData){
                $('#editBOMMatUnit').val(uomData.symbol);
                $('#editBOMMatUnit').attr('unitId',uomData.id);
                $('#precisionUom').text(uomData.symbol);
            });
        });

        //编辑物料项确认按钮事件
        $('#editBomMatSaveBtn').on('click',function () {
            EditBomMatSaveEvent();
        });

        //编辑物料项取消钮事件
        $('#editBomMatCancelBtn').on('click',function () {
            EditBomMatCancelEvent();
        });
    }

    //加载选中的物料项
    function LoadBomMatInfo(){
        var itemCode = GetSelectedRow($("#materialTable")).itemCode;

        var serverUrl = serverPath + "BomsDetail/findBomDetail/";
        var param = {bomId:BOMID,itemCode:itemCode};
        ibcpAjax.Select(serverUrl,param,true,function(result){
            var data = result.data;

            $("#editBOMMatNo").val(data.itemCode);
            $("#editBOMMatNo").attr("readonly",true);
            $("#editMatCodeInput").val(data.code + "(" + data.name + ")");
            $("#editMatCodeInput").attr("codeId",data.codeId);
            $("#editMatCodeInput").attr("code",data.code);
            $("#editBOMMatNum").val(data.quantity);
            $("#editBOMMatNumLock").attr("checked",data.inDepCalc);
            $("#editBOMMatUnit").val(data.uomName);
            $("#editBOMMatUnit").attr("unitId",data.uomId);
            $("#materialPrecision").val(data.precisionId);
            $('#precisionUom').text(data.uomName);
            $("#editBOMWeightType").val(data.weighTypeId);
            $("#editBOMWeightMatType").val(data.materialTypeId);
            $("#editBOMTolType").val(data.toleranceTypeId);
            $("#editBOMTolMax").val(data.toleranceUpper);
            $("#editBOMTolMin").val(data.toleranceLower);
            $("#editBOMformula").val(data.potencyFormula);
        });

    }

    var editBomMatUrl = serverPath + 'BomsDetail/updateBomDetail';

    //确认按钮事件
    function EditBomMatSaveEvent(){
        var no = $("#editBOMMatNo").val();
        var code =  $("#editMatCodeInput").attr("code");
        var codeId =  $("#editMatCodeInput").attr("codeId");
        var num =  $("#editBOMMatNum").val();
        var lock =  $("#editBOMMatNumLock").is(':checked');
        var unitName =  $("#editBOMMatUnit").val();
        var unitId = $("#editBOMMatUnit").attr("unitId");
        var wType =  $("#editBOMWeightType").val();
        var precisionId = $('#materialPrecision').val();
        var wMatType =  $("#editBOMWeightMatType").val();
        var tolType =  $("#editBOMTolType").val();
        var tolMax =  $("#editBOMTolMax").val();
        var tolMin =  $("#editBOMTolMin").val();
        var fml = $("#editBOMformula").val();

        if(code == ''){
            TuLayer.ShowTips('请选择物料',$("#addBOMMatCode"));
            return;
        }
        if(num == ''){
            TuLayer.ShowTips('请选择输入数据量',$("#addBOMMatNum"));
            return;
        }
        if(unitName == ''){
            TuLayer.ShowTips('请选择单位',$("#addBOMMatUnit"));
            return;
        }
        Signature.CallSign(100,function(sid){
            var datas = {'sid':sid,'bomId':BOMID, 'itemCode':no, 'codeId':codeId, 'quantity':num, 'uomId':unitId, 'inDepCalc':lock,
                'weighTypeId':wType, 'materialTypeId':wMatType,'precisionId':precisionId, 'toleranceTypeId':tolType, 'toleranceUpper':tolMax, 'toleranceLower':tolMin,'potencyFormula':fml};
            ibcpAjax.Update(editBomMatUrl,datas,true,function(result){
                TuLayer.ShowOK('修改成功');
                var newId = result.data;
                //关闭签名
                Signature.CloseSign();
                //关闭新增
                EditBomMatCancelEvent();
                //刷新定位新数据行
                RefreshMaterial(newId);

            });
        });

    }

    function EditBomMatCancelEvent(){
        TuLayer.Close();
    }

    return {
        Call : Call
    }
})();







